package edu.nctu.csie.jichang.database.save;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.nctu.csie.jichang.database.dbinfo.LoginInfo;
import edu.nctu.csie.jichang.database.model.cell.DBDatabase;
import edu.nctu.csie.jichang.database.model.cell.DBSchema;
import edu.nctu.csie.jichang.database.model.connection.AbstractDBConnection;
import edu.nctu.csie.jichang.database.model.connection.IDBConnection;


/**
 * SaveSQLDB
 * @author Jichang
 */
public class SaveDDL implements ISave {
	
	private static final Logger LOG = LoggerFactory.getLogger(SaveDDL.class);
	
	/**
	 * (non-Javadoc)
	 * @see edu.nctu.csie.jichang.database.save.ISave#doSave(java.util.LinkedHashMap, com.jichang.dbtools.model.cell.DBDatabase)
	 */
	public void doSave(List<LoginInfo> pConns, DBDatabase pDatabase) throws Exception {
		for(LoginInfo l :pConns){
			IDBConnection tConn = null;
			try {
				tConn = AbstractDBConnection.getInstance(l);
				tConn.setAutoCommit(false);
				if(pDatabase.hasSchema(l.getSchema())){
					saveSchema(tConn, pDatabase.getSchema(l.getSchema()));
				}else{
					LOG.error("Can't find schema " + l.getSchema());
				}
			} catch (Exception e) {
				if(tConn != null) tConn.rollback();
				throw e;
			}finally{
				if(tConn!=null) tConn.close();
			}
		}
	}

	public void saveSchema(IDBConnection pConn,DBSchema pSchema) throws Exception {
//		if (pSchema instanceof DBDDLSchema) {
//			List<String> tSQL = pConn.getDDLSQL((DBDDLSchema) pSchema);
//			for (String s : tSQL) {
//				LogSystem.getInstance().log(s);
//			}
//		}
	}
	
	public void doSave(File pFile, DBDatabase pDatabase) throws Exception {
		throw new Exception("The Object not support this function");
	}
	
}
